package com.cy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cy.bean.UserList;
import com.cy.util.ConnectionFactory;

public class UserListDaoImpl implements UserListDao {

	@Override
	public List<UserList> findAllByPage(int page, String namevalue) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			if (namevalue == null || namevalue.equals("")) {
				String sql = "select * from user limit ?,8";
				psmt = conn.prepareStatement(sql);
				psmt.setInt(1, page);
			} else if (namevalue != null && !namevalue.equals("")) {
				String sql = "select * from user where username=? limit ?,8";
				psmt = conn.prepareStatement(sql);
				psmt.setString(1, namevalue);
				psmt.setInt(2, page);
			}

			rs = psmt.executeQuery();
			List<UserList> users = new ArrayList<>();
			while (rs.next()) {
				UserList user = new UserList();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setSex(rs.getInt("sex"));
				user.setAge(rs.getInt("age"));
				user.setUsername(rs.getString("username"));
				user.setEmail(rs.getString("email"));
				user.setState(rs.getInt("state"));
				users.add(user);
			}
			return users;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return null;
	}

	@Override
	public int findTotal() {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		int total = 0;
		try {

			String sql = "select count(*) as total from user";
			psmt = conn.prepareStatement(sql);
			rs = psmt.executeQuery();
			while (rs.next()) {
				total = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return total;
	}

}
